package com.starsoft.trade.trader.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.starsoft.frame.util.StringUtil;

public class YjbResponse {

	private String funtionId;
	private String msgInfo;
	private int msgNo;

	private List<Map<String, String>> data;

	@SuppressWarnings("unchecked")
	public YjbResponse(String response) {
		int beginIndex = response.indexOf("returnJson");
		int endIndex = response.lastIndexOf("\"}");
		if (beginIndex < 0) {
			throw new RuntimeException("reposnse 格式错误");
		}

		String responseJson = response.substring(beginIndex+13, endIndex);
		try {
			ObjectMapper om = new ObjectMapper();
			om.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
			om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
			Map<String, Object> responseMap = om.readValue(responseJson, Map.class);
			this.funtionId = (String)responseMap.get("function_id");
			this.msgInfo =  (String)responseMap.get("msg_info");
			this.msgNo =  Integer.parseInt((String) responseMap.get("msg_no"));

			String funResponseName = "Func"+funtionId;
			List<Map<String, String>> funResponse = (List<Map<String, String>>) responseMap.get(funResponseName);
			if(funResponse!=null&&funResponse.size()>1){
				data = funResponse.subList(1, funResponse.size());
				checkNullRow();
			} else {
				data = new ArrayList<Map<String,String>>();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void checkNullRow() {
		if(data.size()==1){
			boolean nullRow = true;
			for(String value: data.get(0).values()){
				if(!StringUtil.isEmpty(value)){
					nullRow = false;
					break;
				}
			}
			if(nullRow==true){
				data = new ArrayList<Map<String,String>>();
			}
		}
	}

	public List<Map<String, String>> getData(){
		return data;
	}
	
	public Map<String, String> getData(int i){
		return data.get(i);
	}
	
	public String getFuntionId() {
		return funtionId;
	}

	public void setFuntionId(String funtionId) {
		this.funtionId = funtionId;
	}

	public String getMsgInfo() {
		return msgInfo;
	}

	public void setMsgInfo(String msgInfo) {
		this.msgInfo = msgInfo;
	}

	public int getMsgNo() {
		return msgNo;
	}

	public void setMsgNo(int msgNo) {
		this.msgNo = msgNo;
	}

	
	
}
